<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8" />
    <title>备件管理系统 - 备件管理</title>
    <link rel="stylesheet" href="https://unpkg.com/element-plus/dist/index.css">
</head>
<body>
<div id="app">
    <!-- 页面头部 -->
    <header class="header">
        <h2 style="margin: 0;">备件管理</h2>
    </header>

    <!-- 主体内容 -->
    <main>
        <div style="display: flex; flex-direction: column; gap: 10px; margin-bottom: 10px;">
            <div style="align-self: flex-end;">
                <el-button type="info" size="small" @click="logout">退出</el-button>
            </div>
            <div style="display: flex; justify-content: space-between; align-items: center;">
                <el-button type="primary" @click="showAddDialog = true">新增备件</el-button>
                <el-input v-model="searchQuery" placeholder="请输入搜索内容" style="width: 300px;"></el-input>
            </div>
        </div>

        <!-- 表格 -->
        <el-table :data="filteredSpareParts" border style="width: 100%">
            <el-table-column prop="sparepartid" label="ID"></el-table-column>
            <el-table-column prop="model" label="型号"></el-table-column>
            <el-table-column prop="specification" label="规格"></el-table-column>
            <el-table-column prop="supplierName" label="供应商名称"></el-table-column>
            <el-table-column prop="devicetype" label="设备类型"></el-table-column>
            <el-table-column prop="importancelevel" label="重要性级别"></el-table-column>
            <el-table-column label="操作">
                <template #default="scope">
                    <el-button size="mini" type="danger" @click="deleteSparePart(scope.row.sparepartid)">删除</el-button>
                    <el-button size="mini" type="success" @click="generateQRCode(scope.row.sparepartid)">生成二维码</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 新增弹窗 -->
        <el-dialog v-model="showAddDialog" title="新增备件" width="40%">
            <el-form :model="newSparePart" label-position="left" label-width="100px" style="max-width: 400px;">
                <el-form-item label="型号">
                    <el-input v-model="newSparePart.model"></el-input>
                </el-form-item>
                <el-form-item label="规格">
                    <el-input v-model="newSparePart.specification"></el-input>
                </el-form-item>
                <el-form-item label="供应商ID">
                    <el-input v-model.number="newSparePart.supplierid"></el-input>
                </el-form-item>
                <el-form-item label="设备类型">
                    <el-input v-model="newSparePart.devicetype"></el-input>
                </el-form-item>
                <el-form-item label="重要性级别">
                    <el-input v-model="newSparePart.importancelevel"></el-input>
                </el-form-item>
                <el-button type="primary" @click="addSparePart" style="width: 100%">添加</el-button>
            </el-form>
        </el-dialog>

        <!-- 二维码弹窗 -->
        <el-dialog v-model="showQRCodeDialog" title="二维码" width="30%">
            <div style="text-align: center">
                <img :src="qrCodeImage" alt="二维码" v-if="qrCodeImage" style="width: 200px; height: 200px;" />
                <p>备件ID: {{ selectedSparePartId }}</p>
            </div>
        </el-dialog>
    </main>

    <!-- 底部 -->
    <footer class="footer">
        &copy; 2025 备件管理系统 - 版权所有
    </footer>
</div>

<!-- 引入 Vue + Axios + Element Plus -->
<script src="https://unpkg.com/vue@3.2.36/dist/vue.global.prod.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="https://unpkg.com/element-plus"></script>

<script>
    const { createApp } = Vue;

    const apiClient = axios.create({
        //baseURL: 'http://192.168.143.27:8086',
        //本机地址
        //baseURL: 'http://localhost:8086',
        //服务器 地址
        baseURL: 'http://8.137.85.243:8086',
        timeout: 5000
    });

    const app = createApp({
        data() {
            return {
                spareParts: [],
                newSparePart: {
                    model: '',
                    specification: '',
                    supplierid: null,
                    devicetype: '',
                    importancelevel: ''
                },
                showAddDialog: false,
                searchQuery: '',
                qrCodeImage: "",
                showQRCodeDialog: false,
                selectedSparePartId: null
            };
        },
        computed: {
            filteredSpareParts() {
                if (!this.searchQuery) {
                    return this.spareParts;
                }
                return this.spareParts.filter(item =>
                    item.model.includes(this.searchQuery) ||
                    item.specification.includes(this.searchQuery) ||
                    item.supplierName.includes(this.searchQuery)
                );
            }
        },
        mounted() {
            this.loadSpareParts();
        },
        methods: {
            async loadSpareParts() {
                try {
                    // 获取备件列表
                    const res = await apiClient.get('/api/spareparts/listall');
                    const spareParts = res.data;

                    // 增强数据：获取分类和供应商信息
                    const enrichedSpareParts = await Promise.all(spareParts.map(async (sp) => {
                        try {
                            const categoryRes = await apiClient.get(`/api/sparecategories/findbysparepartid/${sp.sparepartid}`);
                            const supplierRes = await apiClient.get(`/api/suppliers/findbyid/${sp.supplierid}`);

                            return {
                                ...sp,
                                devicetype: categoryRes.data[0]?.devicetype || '未知',
                                importancelevel: categoryRes.data[0]?.importancelevel || '未知',
                                supplierName: supplierRes.data?.name || '未知供应商'
                            };
                        } catch (err) {
                            console.error(`加载备件 ${sp.sparepartid} 失败`, err);
                            return {
                                ...sp,
                                devicetype: '未知',
                                importancelevel: '未知',
                                supplierName: '未知供应商'
                            };
                        }
                    }));

                    this.spareParts = enrichedSpareParts;
                } catch (err) {
                    alert('加载备件失败: ' + err.message);
                }
            },
            async addSparePart() {
                if (!this.newSparePart.model || !this.newSparePart.specification || !this.newSparePart.supplierid ||
                    !this.newSparePart.devicetype || !this.newSparePart.importancelevel) {
                    alert('请填写完整信息');
                    return;
                }

                try {
                    const sparePartRes = await apiClient.post('/api/spareparts/insert', {
                        model: this.newSparePart.model,
                        specification: this.newSparePart.specification,
                        supplierid: this.newSparePart.supplierid
                    });

                    const sparepartid = sparePartRes.data.sparepartid;

                    await apiClient.post('/api/sparecategories/insert', {
                        sparepartid: sparepartid,
                        devicetype: this.newSparePart.devicetype,
                        importancelevel: this.newSparePart.importancelevel
                    });

                    alert('新增成功');
                    this.showAddDialog = false;
                    this.newSparePart = {
                        model: '',
                        specification: '',
                        supplierid: null,
                        devicetype: '',
                        importancelevel: ''
                    };
                    this.loadSpareParts();
                } catch (error) {
                    alert('新增失败: ' + error.message);
                    console.error('新增备件出错:', error);
                }
            },
            async deleteSparePart(id) {
                if (!confirm('确定删除？')) return;
                try {
                    await apiClient.delete(`/api/spareparts/delete/${id}`);
                    this.loadSpareParts();
                } catch (error) {
                    alert('删除失败: ' + error.message);
                }
            },
            async generateQRCode(sparepartid) {
                const scanUrl = `http://8.137.85.243:8086/operation/scan_result.html?result=${sparepartid}`;
                try {
                    const res = await apiClient.get('/api/qrcode/generate', {
                        params: { content: scanUrl }
                    });
                    this.qrCodeImage = res.data;
                    this.selectedSparePartId = sparepartid;
                    this.showQRCodeDialog = true;
                } catch (err) {
                    alert("生成二维码失败");
                    console.error("生成二维码失败:", err);
                }
            },
            logout() {
                window.location.href = '/operator.html';
            }
        }
    });

    app.use(ElementPlus);
    app.mount('#app');
</script>
</body>
</html>
